import struct
from collections import OrderedDict

from ..base import BaseParser
from ...helper import get_price
from ...helper import get_time


class GetHistoryTransactionData(BaseParser):

    def setup(self):
        pass

    def setParams(self, market, code, start, count, date):
        code = code.encode('utf-8') if type(code) is str else code

        if type(date) is (type(date) is str) or (type(date) is bytes):
            date = int(date)

        pkg = bytearray.fromhex(u'0c 01 30 01 00 01 12 00 12 00 b5 0f')
        pkg.extend(struct.pack('<IH6sHH', date, market, code, start, count))

        self.send_pkg = pkg

    def parseResponse(self, body_buf):
        # pos = 0

        pos = 2
        num, = struct.unpack('<H', body_buf[:pos])

        ticks = []

        # skip 4 bytes
        pos += 4

        last_price = 0

        for i in range(num):
            hour, minute, pos = get_time(body_buf, pos)

            price_raw, pos = get_price(body_buf, pos)
            vol, pos = get_price(body_buf, pos)
            side, pos = get_price(body_buf, pos)
            _, pos = get_price(body_buf, pos)

            last_price = last_price + price_raw

            tick = OrderedDict(
                [
                    ('time', '%02d:%02d' % (hour, minute)),
                    ('price', float(last_price) / 100),
                    ('vol', vol),
                    ('side', side),
                ]
            )

            ticks.append(tick)

        return ticks
